//
//  GYConfigDBManager.m
//  research
//
//  Created by 章鱼 on 17/3/28.
//  Copyright © 2017年 simon. All rights reserved.
//

#import "GYConfigDBManager.h"
#import "VBDBManager.h"

// 登录账号信息的保存
static NSString *GYDBConfigLoginAccountInfo  = @"GYDBConfigLoginAccountInfo";
// 判断是否登录状态
static NSString *GYDBConfigIsLogin = @"GYDBConfigIsLogin";
//个人信息的缓存
static NSString *GYDBConfigUserInformation = @"GYDBConfigUserInformation";
//token
static NSString *GYDBConfigToken = @"GYDBConfigToken";

@interface GYConfigDBManager () {
    VBDBManager *_dbMgr;
}

@end
@implementation GYConfigDBManager

+ (id)defaultManager {
    static GYConfigDBManager *s_instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        s_instance = [[GYConfigDBManager alloc] init];
    });
    return s_instance;
}

- (id)init {
    self = [super init];
    if (self) {
        _dbMgr = [VBDBManager defaultMgr];
        // 一定要先获取 dbMgr才能调用
        [self createTables];
    }
    return self;
}

- (void)createTables {
    [[_dbMgr fmDabaseQueue] inDatabase:^(FMDatabase *db) {
        const char *table_sql[] = {
            "CREATE TABLE IF NOT EXISTS config ("
            "key        VARCHAR(256) PRIMARY KEY,"
            "value      VARCHAR(1024)"
            ")"
        };
        BOOL retValue = NO;
        for (int i = 0; i < ARRAYSIZE(table_sql); i ++) {
            retValue = [db executeUpdate:[NSString stringWithUTF8String:table_sql[i]]];
            if (!retValue) {
                NSLog(@"execute sql error.");
                break;
            }
        }
    }];
}

- (void)clearTables {
    [[_dbMgr fmDabaseQueue] inDatabase:^(FMDatabase *db) {
        const char *table_sql[] = {
            "DELETE FROM config"
        };
        BOOL retValue = NO;
        for (int i = 0; i < ARRAYSIZE(table_sql); i ++) {
            retValue = [db executeUpdate:[NSString stringWithUTF8String:table_sql[i]]];
            if (!retValue) {
                NSLog(@"execute sql error.");
                break;
            }
        }
    }];
}

- (void)dropTables {
    [[_dbMgr fmDabaseQueue] inDatabase:^(FMDatabase *db) {
        const char *table_sql[] = {
            "DROP TABLE config"
        };
        BOOL retValue = NO;
        for (int i = 0; i < ARRAYSIZE(table_sql); i ++) {
            retValue = [db executeUpdate:[NSString stringWithUTF8String:table_sql[i]]];
            if (!retValue) {
                NSLog(@"execute sql error.");
                break;
            }
        }
    }];
}

- (BOOL)insertItem:(NSString *)key value:(NSString *)value {
    assert(key && [key length] > 0);
    __block BOOL retValue = NO;
    [[_dbMgr fmDabaseQueue] inDatabase:^(FMDatabase *db) {
        FMResultSet *rs = [db executeQuery:@"SELECT value FROM config WHERE key = ?", key];
        if ([rs next]) {
            retValue = [db executeUpdate:@"UPDATE config SET value = ? WHERE key = ?", value, key];
        } else {
            retValue = [db executeUpdate:@"INSERT INTO config (key, value) VALUES (?,?)", key, value];
        }
        [rs close];
    }];
    
    return retValue;
}

- (BOOL)insertBoolItem:(NSString *)key value:(BOOL)value {
    return [self insertItem:key value:(value ? @"1" : @"0")];
}

- (BOOL)insertIntItem:(NSString *)key value:(NSInteger)value {
    return [self insertItem:key value:[NSString stringWithFormat:@"%ld", (long)value]];
}

- (NSString *)queryItem:(NSString *)key {
    assert(key && [key length] > 0);
    __block NSString *retValue = @"";
    [[_dbMgr fmDabaseQueue] inDatabase:^(FMDatabase *db) {
        FMResultSet *rs = [db executeQuery:@"SELECT value FROM config WHERE key = ?", key];
        if ([rs next]) {
            if (![rs columnIsNull:@"value"]) {
                retValue = [NSString stringWithString:[rs stringForColumn:@"value"]];
            }
        }
        [rs close];
    }];
    
    return retValue;
}

- (BOOL)updateItem:(NSString *)key value:(NSString *)value {
    __block BOOL retValue = NO;
    [[_dbMgr fmDabaseQueue] inDatabase:^(FMDatabase *db) {
        retValue = [db executeUpdate:@"UPDATE config SET value = ? WHERE key = ?", value, key];
    }];
    
    return retValue;
}

- (BOOL)deleteItem:(NSString *)key {
    __block BOOL retValue = NO;
    [[_dbMgr fmDabaseQueue] inDatabase:^(FMDatabase *db) {
        retValue = [db executeUpdate:@"DELETE FROM config WHERE key = ?", key];
    }];
    
    return retValue;
}

#pragma mark - 清除用户数据
- (void)cleanUserData {
    [self deleteLogin];
    [self deleteUserInformation];
    [self deleteToken];

}
#pragma mark -  个人信息
- (void)setUserInformation:(GYUserInfoModel *)model {
    
    [self insertItem:GYDBConfigUserInformation value:[model mj_JSONString]];
    
}
- (GYUserInfoModel *)userInformation {
    NSString *jsonStr = [self queryItem:GYDBConfigUserInformation];
    
    return [GYUserInfoModel mj_objectWithKeyValues:jsonStr];
}
- (void)deleteUserInformation {
    
    [self deleteItem:GYDBConfigUserInformation];
}

#pragma mark - token

- (void)setGYToken:(NSString *)GYToken {
    [self insertItem:GYDBConfigToken value:GYToken];
    
}
- (NSString *)gyToken {
    NSString * jsonToken = [self queryItem:GYDBConfigToken];
    return jsonToken;
    
}
- (void)deleteToken {
    [self deleteItem:GYDBConfigToken];

}
#pragma mark - 是否登录标识
- (void)setLogin:(BOOL)login {
    
    if (login) {
        [self insertItem:GYDBConfigIsLogin value:@"1"];
        return;
    }
    [self insertItem:GYDBConfigIsLogin value:@"0"];
}
- (BOOL)isLogin {
    
    NSString *loginStr = [self queryItem:GYDBConfigIsLogin];
    if ([loginStr isEqualToString:@"1"]) {
        return YES;
    }
    return NO;
}
- (void)deleteLogin {
    
    [self deleteItem:GYDBConfigIsLogin];
}


@end
